<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/12/18 0018
 * Time: 下午 4:38
 */

namespace app\admin\controller;
use app\admin\logic\OrderLogic;
use think\AjaxPage;
use think\Page;
use think\Verify;
use think\Db;
use app\admin\logic\UsersLogic;
use think\Loader;
class Partner extends Base
{
    public  $order_status;
    public  $pay_status;
    public  $shipping_status;
    /*
     * 初始化操作
     */
    public function _initialize() {
        parent::_initialize();
        C('TOKEN_ON',false); // 关闭表单令牌验证
        $this->order_status = C('ORDER_STATUS');
        $this->pay_status = C('PAY_STATUS');
        $this->shipping_status = C('SHIPPING_STATUS');
        // 订单 支付 发货状态
        $this->assign('order_status',$this->order_status);
        $this->assign('pay_status',$this->pay_status);
        $this->assign('shipping_status',$this->shipping_status);
    }
    /**
     * @return mixed 合伙人类型
     */
    public function type(){
        $act = I('get.act','add');
        $this->assign('act',$act);
        $type_id = I('get.type_id');
        if($type_id){
            $type_info = D('user_type')->where('type_id='.$type_id)->find();
            $this->assign('info',$type_info);
        }
        return $this->fetch();
    }
    /**
     * @return mixed 合伙人类型
     */
    public function typeList(){
        $Ad =  M('user_type');
        $p = $this->request->param('p');
        $res = $Ad->order('type_id')->page($p.',10')->select();
        if($res){
            foreach ($res as $val){
                $list[] = $val;
            }
        }
        $this->assign('list',$list);
        $count = $Ad->count();
        $Page = new Page($count,10);
        $show = $Page->show();
        $this->assign('page',$show);
        return $this->fetch();
    }
    /**
     * 合伙人类型添加编辑删除
     */
    public function typeHandle()
    {
        $data = I('post.');
        $userLevelValidate = Loader::validate('UserType');
        $return = ['status' => 0, 'msg' => '参数错误', 'result' => ''];//初始化返回信息
        if ($data['act'] == 'add') {
            if (!$userLevelValidate->batch()->check($data)) {
                $return = ['status' => 0, 'msg' => '添加失败', 'result' => $userLevelValidate->getError()];
            } else {
                $r = D('user_type')->add($data);
                if ($r !== false) {
                    $return = ['status' => 1, 'msg' => '添加成功', 'result' => $userLevelValidate->getError()];
                } else {
                    $return = ['status' => 0, 'msg' => '添加失败，数据库未响应', 'result' => ''];
                }
            }
        }
        if ($data['act'] == 'edit') {
            if (!$userLevelValidate->scene('edit')->batch()->check($data)) {
                $return = ['status' => 0, 'msg' => '编辑失败', 'result' => $userLevelValidate->getError()];
            } else {
                $r = D('user_type')->where('type_id=' . $data['type_id'])->save($data);
                if ($r !== false) {
                    $return = ['status' => 1, 'msg' => '编辑成功', 'result' => $userLevelValidate->getError()];
                } else {
                    $return = ['status' => 0, 'msg' => '编辑失败，数据库未响应', 'result' => ''];
                }
            }
        }
        if ($data['act'] == 'del') {
            $r = D('user_type')->where('type_id=' . $data['type_id'])->delete();
            if ($r !== false) {
                $return = ['status' => 1, 'msg' => '删除成功', 'result' => ''];
            } else {
                $return = ['status' => 0, 'msg' => '删除失败，数据库未响应', 'result' => ''];
            }
        }
        $this->ajaxReturn($return);
    }



    /**
     * @return //合伙人添加编辑删除
     */
    public function partner(){
        $act = I('get.act','add');
        $this->assign('act',$act);
        $user_id = I('get.user_id');
        if($user_id){
            $partner_info = D('users')->where('user_id='.$user_id)->find();
            $type_id = $partner_info['type_id'];
            $typePartner = D('user_type')->where('type_id='.$type_id)->find();
            $this->assign('info',$partner_info);
            $this->assign('typePartner',$typePartner);
        }
        $usersList = M("users")->select();
        $this->assign('usersList',$usersList);
        $userTypeList = M("userType")->select();
        $this->assign('userTypeList',$userTypeList);
        return $this->fetch();
    }
    /**
     * @return mixed 合伙人列表
     */
    public function partnerList(){
        ///*************添加的限制条件*******************************//
        $sql = 'SELECT user_id FROM tp_users WHERE type_id <> 0';
        $arr = DB::query($sql);
        $idsArr = array_column($arr,'user_id');
        $ids = implode(',',$idsArr);
        ///********************************************//
        $count = Db::name('users')->whereIn('user_id',$ids)->count();
        $Page = new Page($count,9);
        $res = Db::name('users')
            ->alias('w')->field('w.*,u.type_name')
            ->join('__USER_TYPE__ u', 'u.type_id = w.type_id', 'INNER')
            ->order("w.user_id desc")
            ->limit($Page->firstRow.','.$Page->listRows)
            ->select();

        if($res){
            foreach ($res as $val){
                if($val['type_id'] <>0){
                    $list[] = $val;
                }
            }
        }
        $this->assign('list',$list);
        $show = $Page->show();
        $this->assign('page',$show);
        return $this->fetch();
    }
    /**
     * 合伙人添加编辑删除
     */
    public function partnerHandle()
    {
        $data = I('post.');
        $userpartnerValidate = Loader::validate('users');
        $return = ['status' => 0, 'msg' => '参数错误', 'result' => ''];//初始化返回信息
        if ($data['act'] == 'add') {
            if (!$userpartnerValidate->batch()->check($data)) {
                $return = ['status' => 0, 'msg' => '添加失败', 'result' => $userpartnerValidate->getError()];
            } else {
                $r = D('users')->where(array('user_id'=>I('user_id')))->save(array('type_id'=>$data['type_id']));
                if ($r !== false) {
                    $return = ['status' => 1, 'msg' => '添加成功', 'result' => $userpartnerValidate->getError()];
                } else {
                    $return = ['status' => 0, 'msg' => '添加失败，数据库未响应', 'result' => ''];
                }
            }
        }
        if ($data['act'] == 'edit') {
            if (!$userpartnerValidate->scene('edit')->batch()->check($data)) {
                $return = ['status' => 0, 'msg' => '编辑失败', 'result' => $userpartnerValidate->getError()];
            } else {
                $r = D('users')->where(array('user_id'=>I('user_id')))->save(array('type_id'=>$data['type_id']));
                if ($r !== false) {
                    $return = ['status' => 1, 'msg' => '编辑成功', 'result' => $userpartnerValidate->getError()];
                } else {
                    $return = ['status' => 0, 'msg' => '编辑失败，数据库未响应', 'result' => ''];
                }
            }
        }
        if ($data['act'] == 'del') {
            $r = D('users')->where(array('user_id'=>I('user_id')))->save(array('type_id'=>$data['type_id']));
            if ($r !== false) {
                $return = ['status' => 1, 'msg' => '删除成功', 'result' => ''];
            } else {
                $return = ['status' => 0, 'msg' => '删除失败，数据库未响应', 'result' => ''];
            }
        }
        $this->ajaxReturn($return);
    }
    /**
     * 提现申请记录
     */
    public function withdrawals()
    {
        $this->get_withdrawals_list();
        return $this->fetch();
    }
    /**
     * 提现申请汇款记录
     */
    public function get_withdrawals_list($status=''){
        $user_id = I('user_id/d');
        $realname = I('realname');
        $bank_card = I('bank_card');
        $create_time = I('create_time');
        $create_time = str_replace("+"," ",$create_time);
        $create_time2 = $create_time  ? $create_time  : date('Y-m-d',strtotime('-1 year')).' - '.date('Y-m-d',strtotime('+1 day'));
        $create_time3 = explode(' - ',$create_time2);
        $this->assign('start_time',$create_time3[0]);
        $this->assign('end_time',$create_time3[1]);
        ////**************新增的限制条件start*****************//////
        $sql = 'SELECT user_id FROM tp_users WHERE type_id <> 0';
        $arr = DB::query($sql);
        $idsArr = array_column($arr,'user_id');
        $ids = implode(',',$idsArr);

        ////**************新增的限制条件end*****************//////

        $where['w.create_time'] =  array(array('gt', strtotime(strtotime($create_time3[0])), array('lt', strtotime($create_time3[1]))));
        $status = empty($status) ? I('status') : $status;
        if(empty($status) || $status === '0'){
            $where['w.status'] =  array('lt',1);
        }
        if($status === '0' || $status > 0) {
            $where['w.status'] = $status;
        }
        $user_id && $where['u.user_id'] = $user_id;
        $realname && $where['w.realname'] = array('like','%'.$realname.'%');
        $bank_card && $where['w.bank_card'] = array('like','%'.$bank_card.'%');
        $export = I('export');
        if($export == 1){
            $strTable ='<table width="500" border="1">';
            $strTable .= '<tr>';
            $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">申请人</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;" width="100">提现金额</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;" width="*">银行名称</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;" width="*">银行账号</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;" width="*">开户人姓名</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;" width="*">申请时间</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;" width="*">提现备注</td>';
            $strTable .= '</tr>';
            $remittanceList = Db::name('withdrawals')->alias('w')->field('w.*,u.nickname')->join('__USERS__ u', 'u.user_id = w.user_id', 'INNER')->where($where)->order("w.id desc")->select();
            if(is_array($remittanceList)){
                foreach($remittanceList as $k=>$val){
                    $strTable .= '<tr>';
                    $strTable .= '<td style="text-align:center;font-size:12px;">'.$val['nickname'].'</td>';
                    $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['money'].' </td>';
                    $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['bank_name'].'</td>';
                    $strTable .= '<td style="vnd.ms-excel.numberformat:@">'.$val['bank_card'].'</td>';
                    $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['realname'].'</td>';
                    $strTable .= '<td style="text-align:left;font-size:12px;">'.date('Y-m-d H:i:s',$val['create_time']).'</td>';
                    $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['remark'].'</td>';
                    $strTable .= '</tr>';
                }
            }
            $strTable .='</table>';
            unset($remittanceList);
            downloadExcel($strTable,'remittance');
            exit();
        }
        $count = Db::name('withdrawals')
            ->alias('w')
            ->join('__USERS__ u', 'u.user_id = w.user_id', 'INNER')
            ->whereIn('u.user_id',$ids)
            ->where($where)
            ->count();
        $Page  = new Page($count,20);
        $list = Db::name('withdrawals')
            ->alias('w')
            ->field('w.*,u.nickname')
            ->join('__USERS__ u', 'u.user_id = w.user_id', 'INNER')
            ->where($where)
            ->whereIn('u.user_id',$ids)
            ->order("w.id desc")
            ->limit($Page->firstRow.','.$Page->listRows)
            ->select();
        $this->assign('create_time',$create_time2);
        $show  = $Page->show();
        $this->assign('show',$show);
        $this->assign('list',$list);
        $this->assign('pager',$Page);
        C('TOKEN_ON',false);
    }
    /**
     * 删除申请记录
     */
    public function delWithdrawals()
    {
        $model = M("withdrawals");
        $model->where('id ='.$_GET['id'])->delete();
        $return_arr = array('status' => 1,'msg' => '操作成功','data'  =>'',);   //$return_arr = array('status' => -1,'msg' => '删除失败','data'  =>'',);
        $this->ajaxReturn($return_arr);
    }

    /**
     * 修改编辑 申请提现
     */
    public  function editWithdrawals(){
        $id = I('id');
        $model = M("withdrawals");
        $withdrawals = $model->find($id);
        $user = M('users')->where("user_id = {$withdrawals[user_id]}")->find();
        if($user['nickname'])
            $withdrawals['user_name'] = $user['nickname'];
        elseif($user['email'])
            $withdrawals['user_name'] = $user['email'];
        elseif($user['mobile'])
            $withdrawals['user_name'] = $user['mobile'];

        $this->assign('user',$user);
        $this->assign('data',$withdrawals);
        return $this->fetch();
    }
    /**
     *  处理会员提现申请
     */
    public function withdrawals_update(){
        $id = I('id/a');
        $data['status']=$status = I('status');
        $data['remark'] = I('remark');
        if($status == 1) $data['check_time'] = time();
        if($status != 1) $data['refuse_time'] = time();
        $r = M('withdrawals')->where('id in ('.implode(',', $id).')')->update($data);
        if($r){
            $this->ajaxReturn(array('status'=>1,'msg'=>"操作成功"),'JSON');
        }else{
            $this->ajaxReturn(array('status'=>0,'msg'=>"操作失败"),'JSON');
        }
    }
    // 用户申请提现
    public function transfer(){
        $id = I('selected/a');
        if(empty($id))$this->error('请至少选择一条记录');
        $atype = I('atype');
        if(is_array($id)){
            $withdrawals = M('withdrawals')->where('id in ('.implode(',', $id).')')->select();
        }else{
            $withdrawals = M('withdrawals')->where(array('id'=>$id))->select();
        }
        $alipay['batch_num'] = 0;
        $alipay['batch_fee'] = 0;
        foreach($withdrawals as $val){
            $user = M('users')->where(array('user_id'=>$val['user_id']))->find();
            if($user['user_money'] < $val['money'])
            {
                $data = array('status'=>-2,'remark'=>'账户余额不足');
                M('withdrawals')->where(array('id'=>$val['id']))->save($data);
                $this->error('账户余额不足');
            }else{
                $rdata = array('type'=>1,'money'=>$val['money'],'log_type_id'=>$val['id'],'user_id'=>$val['user_id']);
                if($atype == 'online'){
                    header("Content-type: text/html; charset=utf-8");
                    exit("请联系TPshop官网客服购买高级版支持此功能");
                }else{
                    accountLog($val['user_id'], ($val['money'] * -1), 0,"管理员处理用户提现申请");//手动转账，默认视为已通过线下转方式处理了该笔提现申请
                    $r = M('withdrawals')->where(array('id'=>$val['id']))->save(array('status'=>2,'pay_time'=>time()));
                    expenseLog($rdata);//支出记录日志
                }
            }
        }
        if($alipay['batch_num']>0){
            //支付宝在线批量付款
            include_once  PLUGIN_PATH."payment/alipay/alipay.class.php";
            $alipay_obj = new \alipay();
            $alipay_obj->transfer($alipay);
        }
        $this->success("操作成功!",U('remittance'),3);
    }
    /**
     *  转账汇款记录
     */
    public function remittance(){
        $status = I('status',1);
        $this->assign('status',$status);
        $this->get_withdrawals_list($status);
        return $this->fetch();
    }
    /**
     * @return mixed 充值记录
     */
    public function recharge(){
        $timegap = urldecode(I('timegap'));
        $nickname = I('nickname');
        ///*************添加的限制条件*******************************//
        $sql = 'SELECT user_id FROM tp_users WHERE type_id <> 0';
        $arr = DB::query($sql);
        $idsArr = array_column($arr,'user_id');
        $ids = implode(',',$idsArr);
        ///********************************************//
        $map = array();
        if($timegap){
            $gap = explode(',', $timegap);
            $begin = $gap[0];
            $end = $gap[1];
            $map['ctime'] = array('between',array(strtotime($begin),strtotime($end)));
        }
        if($nickname){
            $map['nickname'] = array('like',"%$nickname%");
        }
        $count = M('recharge')->where($map)->whereIn('user_id',$ids)->count();
        $page = new Page($count);
        $lists  = M('recharge')
            ->where($map)
            ->whereIn('user_id',$ids)
            ->order('ctime desc')
            ->limit($page->firstRow.','.$page->listRows)
            ->select();
//        echo "<pre>";
//        print_r(DB::getLastSql());
//        exit;
        $this->assign('page',$page->show());
        $this->assign('pager',$page);
        $this->assign('lists',$lists);
        return $this->fetch();
    }


    /**
        *订单首页
        */
    public function index(){
        $begin = date('Y-m-d',strtotime("-1 year"));//30天前
        $end = date('Y/m/d',strtotime('+1 days'));
        $this->assign('timegap',$begin.'-'.$end);
        return $this->fetch();
    }
    /**
     *Ajaxindex首页
     */
    public function ajaxindex(){
        $orderLogic = new OrderLogic();
        $timegap = I('timegap');
        if($timegap){
            $gap = explode('-', $timegap);
            $begin = strtotime($gap[0]);
            $end = strtotime($gap[1]);
        }else{
            //@new 新后台UI参数
            $begin = strtotime(I('add_time_begin'));
            $end = strtotime(I('add_time_end'));
        }

        // 搜索条件
        $condition = array();
        $keyType = I("keytype");
        $keywords = I('keywords','','trim');

        $consignee =  ($keyType && $keyType == 'consignee') ? $keywords : I('consignee','','trim');
        $consignee ? $condition['consignee'] = trim($consignee) : false;

        if($begin && $end){
            $condition['add_time'] = array('between',"$begin,$end");
        }
        $condition['order_prom_type'] = array('lt',5);
        $order_sn = ($keyType && $keyType == 'order_sn') ? $keywords : I('order_sn') ;
        $order_sn ? $condition['order_sn'] = trim($order_sn) : false;

        I('order_status') != '' ? $condition['order_status'] = I('order_status') : false;
        I('pay_status') != '' ? $condition['pay_status'] = I('pay_status') : false;
        I('pay_code') != '' ? $condition['pay_code'] = I('pay_code') : false;
        I('shipping_status') != '' ? $condition['shipping_status'] = I('shipping_status') : false;
        I('user_id') ? $condition['user_id'] = trim(I('user_id')) : false;
        $sort_order = I('order_by','DESC').' '.I('sort');

        ///*************添加的限制条件*******************************//
        $sql = 'SELECT user_id FROM tp_users WHERE type_id <> 0';
        $arr = DB::query($sql);
        $idsArr = array_column($arr,'user_id');
        $ids = implode(',',$idsArr);
        ///********************************************//



        $count = M('order')->where($condition)->whereIn('user_id',$ids)->count();
        $Page  = new AjaxPage($count,20);
        $show = $Page->show();
        $whereIn = array('user_id',$ids);
        //获取订单列表
        $orderList = $orderLogic->getpartnerList($condition,$whereIn,$sort_order,$Page->firstRow,$Page->listRows);
//        echo "<pre>";
//        print_r(DB::getLastSql());
//        exit;
        $this->assign('orderList',$orderList);
        $this->assign('page',$show);// 赋值分页输出
        $this->assign('pager',$Page);
        return $this->fetch();
    }
    /**
     * 处理表单提交过来的数据
     */
    public function export_order()
    {
        //搜索条件
        $consignee = I('consignee');
        $order_sn =  I('order_sn');
        $timegap = I('timegap');
        $order_status = I('order_status');
        $order_ids = I('order_ids');
        $where = array();//搜索条件
        if($consignee){
            $where['consignee'] = ['like','%'.$consignee.'%'];
        }
        if($order_sn){
            $where['order_sn'] = $order_sn;
        }
        if($order_status){
            $where['order_status'] = $order_status;
        }
        if($timegap){
            $gap = explode('-', $timegap);
            $begin = strtotime($gap[0]);
            $end = strtotime($gap[1]);
            $where['add_time'] = ['between',[$begin, $end]];
        }
        if($order_ids){
            $where['order_id'] = ['in', $order_ids];
        }


        ///*************添加的限制条件*******************************//
        $sql = 'SELECT user_id FROM tp_users WHERE type_id <> 0';
        $arr = DB::query($sql);
        $idsArr = array_column($arr,'user_id');
        $ids = implode(',',$idsArr);
        ///********************************************//

        $orderList = Db::name('order')->field("*,FROM_UNIXTIME(add_time,'%Y-%m-%d') as create_time")->where($where)->whereIn('user_id',$ids)->order('order_id')->select();
        $strTable ='<table width="500" border="1">';
        $strTable .= '<tr>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">订单编号</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="100">日期</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">收货人</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">收货地址</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">电话</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">订单金额</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">实际支付</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">支付方式</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">支付状态</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">发货状态</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">商品数量</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">商品信息</td>';
        $strTable .= '</tr>';
        if(is_array($orderList)){
            $region	= get_region_list();
            foreach($orderList as $k=>$val){
                $strTable .= '<tr>';
                $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['order_sn'].'</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['create_time'].' </td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['consignee'].'</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'."{$region[$val['province']]},{$region[$val['city']]},{$region[$val['district']]},{$region[$val['twon']]}{$val['address']}".' </td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['mobile'].'</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['goods_price'].'</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['order_amount'].'</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['pay_name'].'</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$this->pay_status[$val['pay_status']].'</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$this->shipping_status[$val['shipping_status']].'</td>';
                $orderGoods = D('order_goods')->where('order_id='.$val['order_id'])->select();
                $strGoods="";
                $goods_num = 0;
                foreach($orderGoods as $goods){
                    $goods_num = $goods_num + $goods['goods_num'];
                    $strGoods .= "商品编号：".$goods['goods_sn']." 商品名称：".$goods['goods_name'];
                    if ($goods['spec_key_name'] != '') $strGoods .= " 规格：".$goods['spec_key_name'];
                    $strGoods .= "<br />";
                }
                unset($orderGoods);
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$goods_num.' </td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$strGoods.' </td>';
                $strTable .= '</tr>';
            }
        }
        $strTable .='</table>';
        unset($orderList);
        downloadExcel($strTable,'order');
        exit();
    }
    /**
     * 添加一笔订单
     */
    public function add_order()
    {
        $order = array();
        //  获取省份
        $province = M('region')->where(array('parent_id'=>0,'level'=>1))->select();
        //  获取订单城市
        $city =  M('region')->where(array('parent_id'=>$order['province'],'level'=>2))->select();
        //  获取订单地区
        $area =  M('region')->where(array('parent_id'=>$order['city'],'level'=>3))->select();
        //  获取配送方式
        $shipping_list = M('plugin')->where(array('status'=>1,'type'=>'shipping'))->select();
        //  获取支付方式
        $payment_list = M('plugin')->where(array('status'=>1,'type'=>'payment'))->select();
        if(IS_POST)
        {
            $order['user_id'] = I('user_id');// 用户id 可以为空
            $order['consignee'] = I('consignee');// 收货人
            $order['province'] = I('province'); // 省份
            $order['city'] = I('city'); // 城市
            $order['district'] = I('district'); // 县
            $order['address'] = I('address'); // 收货地址
            $order['mobile'] = I('mobile'); // 手机
            $order['invoice_title'] = I('invoice_title');// 发票
            $order['admin_note'] = I('admin_note'); // 管理员备注
            $order['order_sn'] = date('YmdHis').mt_rand(1000,9999); // 订单编号;
            $order['admin_note'] = I('admin_note'); //
            $order['add_time'] = time(); //
            $order['shipping_code'] = I('shipping');// 物流方式
            $order['shipping_name'] = M('plugin')->where(array('status'=>1,'type'=>'shipping','code'=>I('shipping')))->getField('name');
            $order['pay_code'] = I('payment');// 支付方式
            $order['pay_name'] = M('plugin')->where(array('status'=>1,'type'=>'payment','code'=>I('payment')))->getField('name');

            $goods_id_arr = I("goods_id/a");
            $orderLogic = new OrderLogic();
            $order_goods = $orderLogic->get_spec_goods($goods_id_arr);
            $result = calculate_price($order['user_id'],$order_goods,$order['shipping_code'],0,$order[province],$order[city],$order[district],0,0,0);
            if($result['status'] < 0)
            {
                $this->error($result['msg']);
            }

            $order['goods_price']    = $result['result']['goods_price']; // 商品总价
            $order['shipping_price'] = $result['result']['shipping_price']; //物流费
            $order['order_amount']   = $result['result']['order_amount']; // 应付金额
            $order['total_amount']   = $result['result']['total_amount']; // 订单总价

            // 添加订单
            $order_id = M('order')->add($order);
            $order_insert_id = DB::getLastInsID();
            if($order_id)
            {
                foreach($order_goods as $key => $val)
                {
                    $val['order_id'] = $order_id;
                    $rec_id = M('order_goods')->add($val);
                    if(!$rec_id)
                        $this->error('添加失败');
                }

                M('order_action')->add([
                    'order_id'      => $order_id,
                    'action_user'   => session('admin_id'),
                    'order_status'  => 0,  //待支付
                    'shipping_status' => 0, //待确认
                    'action_note'   => $order['admin_note'],
                    'status_desc'   => '提交订单',
                    'log_time'      => time()
                ]);
                $this->success('添加商品成功',U("Admin/Order/detail",array('order_id'=>$order_insert_id)));
                exit();
            }
            else{
                $this->error('添加失败');
            }
        }
        $this->assign('shipping_list',$shipping_list);
        $this->assign('payment_list',$payment_list);
        $this->assign('province',$province);
        $this->assign('city',$city);
        $this->assign('area',$area);
        return $this->fetch();
    }
    /**
     * @return mixed 退款单
     */
    public function refund_order_list(){
        $orderLogic = new OrderLogic();
        $condition = array();
        I('consignee') ? $condition['consignee'] = trim(I('consignee')) : false;
        I('order_sn') != '' ? $condition['order_sn'] = trim(I('order_sn')) : false;
        $condition['shipping_status'] = 0;
        $condition['order_status'] = 3;
        $condition['pay_status'] = array('gt',0);


        ///*************添加的限制条件*******************************//
        $sql = 'SELECT user_id FROM tp_users WHERE type_id <> 0';
        $arr = DB::query($sql);
        $idsArr = array_column($arr,'user_id');
        $ids = implode(',',$idsArr);
        ///********************************************//


        $count = M('order')->where($condition)->whereIn('user_id',$ids)->count();

        $Page  = new Page($count,10);
        //搜索条件下 分页赋值
        foreach($condition as $key=>$val) {
            if(!is_array($val)){
                $Page->parameter[$key]   =   urlencode($val);
            }
        }
        $show = $Page->show();
        $orderList = M('order')->where($condition)->whereIn('user_id',$ids)->limit($Page->firstRow.','.$Page->listRows)->order('add_time DESC')->select();
//        echo "<pre>";
//        print_r($orderList);
//        exit;
        $this->assign('orderList',$orderList);
        $this->assign('page',$show);// 赋值分页输出
        $this->assign('pager',$Page);
        return $this->fetch();
    }

    public function refund_order_info($order_id){
        $orderLogic = new OrderLogic();
        $order = $orderLogic->getOrderInfo($order_id);
        $orderGoods = $orderLogic->getOrderGoods($order_id);
        $this->assign('order',$order);
        $this->assign('orderGoods',$orderGoods);
        return $this->fetch();
    }
    //取消订单退款原路退回
    public function refund_order(){
        $data = I('post.');
        $orderLogic = new OrderLogic();
        $order = $orderLogic->getOrderInfo($data['order_id']);
        if(!order){
            $this->error('订单不存在或参数错误');
        }
        if($data['pay_status'] == 3){
            if($data['refund_type'] == 1){
                //取消订单退款退余额
                if(updateRefundOrder($order,1)){
                    $this->success('成功退款到账户余额');
                }else{
                    $this->error('退款失败');
                }
            }
            if($data['refund_type']== 0){
                //取消订单支付原路退回
                if($order['pay_code'] == 'weixin' || $order['pay_code'] == 'alipay' || $order['pay_code'] == 'alipayMobile'){
                    header("Content-type: text/html; charset=utf-8");
                    exit("请联系TPshop官网客服购买高级版支持此功能");
                }else{
                    $this->error('该订单支付方式不支持在线退回');
                }
            }
        }else{
            M('order')->where(array('order_id'=>$order['order_id']))->save($data);
            $this->success('拒绝退款操作成功');
        }
    }
    /**
       * 价钱修改
       */
    public function editprice($order_id){
        $orderLogic = new OrderLogic();
        $order = $orderLogic->getOrderInfo($order_id);
        $this->editable($order);
        if(IS_POST){
            $admin_id = session('admin_id');
            if(empty($admin_id)){
                $this->error('非法操作');
                exit;
            }
            $update['discount'] = I('post.discount');
            $update['shipping_price'] = I('post.shipping_price');
            $update['order_amount'] = $order['goods_price'] + $update['shipping_price'] - $update['discount'] - $order['user_money'] - $order['integral_money'] - $order['coupon_price'];
            $row = M('order')->where(array('order_id'=>$order_id))->save($update);
            if(!$row){
                $this->success('没有更新数据',U('Admin/Partner/editprice',array('order_id'=>$order_id)));
            }else{
                $this->success('操作成功',U('Admin/Partner/detail',array('order_id'=>$order_id)));
            }
            exit;
        }
        $this->assign('order',$order);
        return $this->fetch();
    }
    /**
     * 检测订单是否可以编辑
     * @param $order
     */
    private function editable($order){
        if($order['shipping_status'] != 0){
            $this->error('已发货订单不允许编辑');
            exit;
        }
        return;
    }
    /**
     * 订单详情
     * @param int $id 订单id
     */
    public function detail($order_id){
        $orderLogic = new OrderLogic();
        $order = $orderLogic->getOrderInfo($order_id);
        $orderGoods = $orderLogic->getOrderGoods($order_id);
        $button = $orderLogic->getOrderButton($order);
        // 获取操作记录
        $action_log = M('order_action')->where(array('order_id'=>$order_id))->order('log_time desc')->select();
        $has_user = false;
        $adminIds = [];
        //查找用户昵称
        foreach ($action_log as $k => $v){
            if ($v['action_user']) {
                $adminIds[$k] = $v['action_user'];
            } else {
                $has_user = true;
            }
        }
        if($adminIds && count($adminIds) > 0){
            $admins = M("admin")->where("admin_id in (".implode(",",$adminIds).")")->getField("admin_id , user_name", true);
        }
        if($has_user){
            $user = M("users")->field('user_id,nickname')->where(['user_id'=>$order['user_id']])->find();
        }
        $this->assign('admins',$admins);
        $this->assign('user', $user);
        $this->assign('order',$order);
        $this->assign('action_log',$action_log);
        $this->assign('orderGoods',$orderGoods);
        $split = count($orderGoods) >1 ? 1 : 0;
        foreach ($orderGoods as $val){
            if($val['goods_num']>1){
                $split = 1;
            }
        }
        $this->assign('split',$split);
        $this->assign('button',$button);
        return $this->fetch();
    }




    /**
     * 退货单列表
     */
    public function return_list(){
        return $this->fetch();
    }
    /**
     * ajax 退货单列表
     */
    public function ajax_return_list(){
        // 搜索条件
        $order_sn =  trim(I('order_sn'));
        $order_by = I('order_by') ? I('order_by') : 'addtime';
        $sort_order = I('sort_order') ? I('sort_order') : 'desc';
        $status =  I('status');

        $where = " 1 = 1 ";
        $order_sn && $where.= " and order_sn like '%$order_sn%' ";
        empty($order_sn)&& !empty($status) && $where.= " and status = '$status' ";

        ///*************添加的限制条件*******************************//
        $sql = 'SELECT user_id FROM tp_users WHERE type_id <> 0';
        $arr = DB::query($sql);
        $idsArr = array_column($arr,'user_id');
        $ids = implode(',',$idsArr);
      ///********************************************//

        $count = M('return_goods')->whereIn('user_id',$ids)->where($where)->count();
        $Page  = new AjaxPage($count,13);
        $show = $Page->show();
        $list = M('return_goods')->where($where)->whereIn('user_id',$ids)->order("$order_by $sort_order")->limit("{$Page->firstRow},{$Page->listRows}")->select();
        $goods_id_arr = get_arr_column($list, 'goods_id');
        if(!empty($goods_id_arr)){
            $goods_list = M('goods')->where("goods_id in (".implode(',', $goods_id_arr).")")->getField('goods_id,goods_name');
        }
        $state = C('REFUND_STATUS');
        $this->assign('state',$state);
        $this->assign('goods_list',$goods_list);
        $this->assign('list',$list);
        $this->assign('pager',$Page);
        $this->assign('page',$show);// 赋值分页输出
        return $this->fetch();
    }
    /**
     * 退换货操作
     */
    public function return_info()
    {
        $orderLogic = new OrderLogic();
        $return_id = I('id');
        $return_goods = M('return_goods')->where("id= $return_id")->find();
        if(!$return_goods)
        {
            $this->error('非法操作!');
            exit;
        }
        $user = M('users')->where("user_id = {$return_goods[user_id]}")->find();
        $goods = M('goods')->where("goods_id = {$return_goods[goods_id]}")->find();
        $type_msg = array('仅退款','退货退款','换货');
        $status_msg = C('REFUND_STATUS');
        if(IS_POST)
        {
            $data = I('post.');
            if($return_goods['type'] == 2 && $return_goods['is_receive'] == 1){
                $data['seller_delivery']['express_time'] = date('Y-m-d H:i:s');
                $data['seller_delivery'] = serialize($data['seller_delivery']); //换货的物流信息
            }
            $note ="退换货:{$type_msg[$return_goods['type']]}, 状态:{$status_msg[$data['status']]},处理备注：{$data['remark']}";
            $result = M('return_goods')->where("id= $return_id")->save($data);
            if($result && $data['status']==1)
            {
                //审核通过才更改订单商品状态，进行退货，退款时要改对应商品修改库存
                $order = \app\common\model\Order::get($return_goods['order_id']);
                $commonOrderLogic = new \app\common\logic\OrderLogic();
                $commonOrderLogic->alterReturnGoodsInventory($order,$return_goods['rec_id']); //审核通过，恢复原来库存
                if($return_goods['type'] < 2){
                    $orderLogic->disposereRurnOrderCoupon($return_goods); // 是退货可能要处理优惠券
                }
            }
            $orderLogic->orderActionLog($return_goods['order_id'],'退换货',$note);
            $this->success('修改成功!');
            exit;
        }
        $return_goods['seller_delivery'] = unserialize($return_goods['seller_delivery']);  //订单的物流信息，服务类型为换货会显示
        if($return_goods['imgs']) $return_goods['imgs'] = explode(',', $return_goods['imgs']);
        $this->assign('id',$return_id); // 用户
        $this->assign('user',$user); // 用户
        $this->assign('goods',$goods);// 商品
        $this->assign('return_goods',$return_goods);// 退换货
        $order = M('order')->where(array('order_id'=>$return_goods['order_id']))->find();
        $this->assign('order',$order);//退货订单信息
        return $this->fetch();
    }
    /**
     * 删除某个退换货申请
     */
    public function return_del(){
        $id = I('get.id');
        M('return_goods')->where("id = $id")->delete();
        $this->success('成功删除!');
    }
    /**
     * 退货，余额+积分支付
     * 有用三方金额支付的不走这个方法
     */
    public function refund_balance(){
        $data = I('POST.');
        $return_goods = M('return_goods')->where(array('rec_id'=>$data['rec_id']))->find();
        if(empty($return_goods)) $this->ajaxReturn(['status'=>0,'msg'=>"参数有误"]);
        M('return_goods')->where(array('rec_id'=>$data['rec_id']))->save($data);
        updateRefundGoods($data['rec_id'],1);//售后商品退款
        $this->ajaxReturn(['status'=>1,'msg'=>"操作成功",'url'=>U("Admin/Order/return_list")]);

    }

    //售后退款原路退回
    public function refund_back(){
        $return_id = I('id');
        $return_goods = M('return_goods')->where("id= $return_id")->find();
        $rec_goods = M('order_goods')->where(array('order_id'=>$return_goods['order_id'],'goods_id'=>$return_goods['goods_id']))->find();
        $order = M('order')->where(array('order_id'=>$rec_goods['order_id']))->find();
        if($order['pay_code'] == 'weixin' || $order['pay_code'] == 'alipay' || $order['pay_code'] == 'alipayMobile'){
            $orderLogic = new OrderLogic();
            $return_goods['refund_money'] = $orderLogic->getRefundGoodsMoney($return_goods);
            if($order['pay_code'] == 'weixin'){
                include_once  PLUGIN_PATH."payment/weixin/weixin.class.php";
                $payment_obj =  new \weixin();
                $data = array('transaction_id'=>$order['transaction_id'],'total_fee'=>$order['order_amount'],'refund_fee'=>$return_goods['refund_money']);
                $result = $payment_obj->payment_refund($data);
                if($result['return_code'] == 'SUCCESS'  && $result['result_code' == 'SUCCESS']){
                    updateRefundGoods($return_goods['rec_id']);//订单商品售后退款
                    $this->success('退款成功');
                }else{
                    $this->error($result['return_msg']);
                }
            }else{
                include_once  PLUGIN_PATH."payment/alipay/alipay.class.php";
                $payment_obj = new \alipay();
                $detail_data = $order['transaction_id'].'^'.$return_goods['refund_money'].'^'.'用户申请订单退款';
                $data = array('batch_no'=>date('YmdHi').$rec_goods['rec_id'],'batch_num'=>1,'detail_data'=>$detail_data);
                $payment_obj->payment_refund($data);
            }
        }else{
            $this->error('该订单支付方式不支持在线退回');
        }
    }

    /**
     * @return mixed 订单日志
     */
    public function order_log(){
        $timegap = urldecode(I('timegap'));
        if($timegap){
            $gap = explode('-', $timegap);
            $timegap_begin = $gap[0];
            $timegap_end = $gap[1];
            $begin = strtotime($timegap_begin);
            $end = strtotime($timegap_end);
        }else{
            //@new 兼容新模板
            $timegap_begin = urldecode(I('timegap_begin'));
            $timegap_end = urldecode(I('timegap_end'));
            $begin = strtotime($timegap_begin);
            $end = strtotime($timegap_end);
        }
        $condition = array();
        $log =  M('order_action');
        if($begin && $end){
            $condition['log_time'] = array('between',"$begin,$end");
        }
        $admin_id = I('admin_id');
        if($admin_id >0 ){
            $condition['action_user'] = $admin_id;
        }

///*************添加的限制条件*******************************//
        $sql = 'SELECT user_id FROM tp_users WHERE type_id <> 0';
        $arr = DB::query($sql);
        $idsArr = array_column($arr,'user_id');
        $ids = implode(',',$idsArr);

        $sql = 'SELECT * FROM `tp_order` WHERE `user_id` IN ('.$ids.') ';
        $orderList = DB::query($sql);
       $orderIdsArr = array_column($orderList,'order_id');
       $orderIds = implode(',',$orderIdsArr);
///********************************************//
        $count = $log->where($condition)->whereIn('order_id',$orderIds)->count();
        $Page = new Page($count,20);

        foreach($condition as $key=>$val) {
            $Page->parameter[$key] = urlencode($begin.'_'.$end);
        }
        $show = $Page->show();
        $list = $log->where($condition)->whereIn('order_id',$orderIds)->order('action_id desc')->limit($Page->firstRow.','.$Page->listRows)->select();
        $orderIds = [];
        foreach ($list as $log) {
            if (!$log['action_user']) {
                $orderIds[] = $log['order_id'];
            }
        }
        if ($orderIds) {
            $users = M("users")->alias('u')->join('__ORDER__ o', 'o.user_id = u.user_id')->getField('o.order_id,u.nickname');
        }
        $this->assign('timegap_begin',$timegap_begin);
        $this->assign('timegap_end',$timegap_end);
        $this->assign('users',$users);
        $this->assign('list',$list);
        $this->assign('pager',$Page);
        $this->assign('page',$show);
        $admin = M('admin')->getField('admin_id,user_name');
        $this->assign('admin',$admin);
        return $this->fetch();
    }

    public function log(){
        $p = I('p/d',1);
        $logs = DB::name('partner_log')
            ->alias('l')
            ->join('__USERS__ a','a.user_id =l.user_id')
            ->order('log_time DESC')
            ->page($p.',20')->select();
        $this->assign('list',$logs);
        $count = DB::name('partner_log')->count();
        $Page = new Page($count,20);
        $show = $Page->show();
        $this->assign('pager',$Page);
        $this->assign('page',$show);
        return $this->fetch();
    }
    /**
     * @return //合伙人会员添加编辑删除
     */
    public function huiyuan(){
        $act = I('get.act','add');
        $this->assign('act',$act);
        $user_id = I('get.user_id');
        if($user_id){
            $partner_info = D('users')->where('user_id='.$user_id)->find();
            $type_id = $partner_info['type_id'];
            $typePartner = D('user_type')->where('type_id='.$type_id)->find();
            $this->assign('info',$partner_info);
            $this->assign('typePartner',$typePartner);
        }
        $usersList = M("users")->select();
        $this->assign('usersList',$usersList);
        $userTypeList = M("userType")->select();
        $this->assign('userTypeList',$userTypeList);
        return $this->fetch();
    }
    /**
     * @return mixed 合伙人会员列表
     */
    public function huiyuanList(){
        ///*************添加的限制条件*******************************//
        $sql = 'SELECT user_id FROM tp_users WHERE type_id <> 0';
        $arr = DB::query($sql);
        $idsArr = array_column($arr,'user_id');
        $ids = implode(',',$idsArr);
        ///********************************************//
        $count = Db::name('users')->whereIn('user_id',$ids)->count();
        $Page = new Page($count,9);
        $res = Db::name('users')
            ->alias('w')->field('w.*,u.type_name')
            ->join('__USER_TYPE__ u', 'u.type_id = w.type_id', 'INNER')
            ->whereIn('user_id',$ids)
            ->order("w.user_id desc")
            ->limit($Page->firstRow.','.$Page->listRows)
            ->select();

        if($res){
            foreach ($res as $val){
                if($val['type_id'] <>0){
                    $list[] = $val;
                }
            }
        }
        $this->assign('list',$list);
        $show = $Page->show();
        $this->assign('page',$show);
        return $this->fetch();
    }

    public function huiyuanList_detail()
    {


        $user_id = I('user_id/d');

        //通过合伙人id找到   users表里面找出first_leader 是合伙人id的用户
        $count =Db::name('users')
            ->where(['first_leader|second_leader|third_leader'=>$user_id])
            ->count();
        $Page = new Page($count,9);
        $res = Db::name('users')
            ->alias('w')
            ->field('w.*,u.type_name')
            ->join('__USER_TYPE__ u', 'u.type_id = w.type_id','left')
            ->where(['first_leader|second_leader|third_leader'=>$user_id])
            ->order("w.user_id desc")
            ->limit($Page->firstRow.','.$Page->listRows)
            ->select();

        $this->assign('list',$res);
        $show = $Page->show();
        $this->assign('page',$show);
        return $this->fetch();
    }
    /**
     * 合伙人会员添加编辑删除
     */
    public function huiyuanListHandle()
    {
        $data = I('post.');
        $userpartnerValidate = Loader::validate('users');
        $return = ['status' => 0, 'msg' => '参数错误', 'result' => ''];//初始化返回信息
        if ($data['act'] == 'add') {
            if (!$userpartnerValidate->batch()->check($data)) {
                $return = ['status' => 0, 'msg' => '添加失败', 'result' => $userpartnerValidate->getError()];
            } else {
                $r = D('users')->where(array('user_id'=>I('user_id')))->save(array('type_id'=>$data['type_id']));
                if ($r !== false) {
                    $return = ['status' => 1, 'msg' => '添加成功', 'result' => $userpartnerValidate->getError()];
                } else {
                    $return = ['status' => 0, 'msg' => '添加失败，数据库未响应', 'result' => ''];
                }
            }
        }
        if ($data['act'] == 'edit') {
            if (!$userpartnerValidate->scene('edit')->batch()->check($data)) {
                $return = ['status' => 0, 'msg' => '编辑失败', 'result' => $userpartnerValidate->getError()];
            } else {
                $r = D('users')->where(array('user_id'=>I('user_id')))->save(array('type_id'=>$data['type_id']));
                if ($r !== false) {
                    $return = ['status' => 1, 'msg' => '编辑成功', 'result' => $userpartnerValidate->getError()];
                } else {
                    $return = ['status' => 0, 'msg' => '编辑失败，数据库未响应', 'result' => ''];
                }
            }
        }
        if ($data['act'] == 'del') {
            
            $r = D('users')->where(array('user_id'=>I('user_id')))->find();
            if($r['third_leader'] !== ''){
                $r = D('users')->where(array('user_id'=>I('user_id')))->save(array('third_leader'=>'0'));
            }
            if ($r['second_leader'] !== ''){
                $r = D('users')->where(array('user_id'=>I('user_id')))->save(array('second_leader'=>'0'));
            }
            if ($r['first_leader'] !== ''){
                $r = D('users')->where(array('user_id'=>I('user_id')))->save(array('first_leader'=>'0'));
            }

            if ($r !== false) {
                $return = ['status' => 1, 'msg' => '删除成功', 'result' => ''];
            } else {
                $return = ['status' => 0, 'msg' => '删除失败，数据库未响应', 'result' => ''];
            }
        }
        $this->ajaxReturn($return);
    }

}